package com.jy.rhin.infra.repo.document.content;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jy.common.UIDWorker;
import com.jy.rhin.domain.document.content.DocumentContentDao;
import com.jy.rhin.domain.document.content.entity.DocumentContentDO;
import com.jy.rhin.infra.repo.document.content.mapper.DocumentContentMapper;
import com.jy.rhin.infra.repo.document.content.po.DocumentContentPO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author dhl
 * @date 2022/6/1
 * @Description
 */
@Service
public class DocumentContentDaoImpl implements DocumentContentDao {

    @Resource
    UIDWorker uidWorker;
    @Resource
    private DocumentContentMapper documentContentMapper;

    /**
     * 批量保存 一个提交集可能提交多份文档
     * 为保证文档幂等性，需要逐个文档进行insertOrUpdate操作，不适合用批量更新，固采取遍历操作
     *
     * @param contentList
     */
    @Override
    public void batchSave(List<DocumentContentDO> contentList) {
        contentList.forEach(this::saveContent);
    }

    /**
     * 保存文档，根据uniqueId做幂等校验
     *
     * @param contentDO
     */
    private void saveContent(DocumentContentDO contentDO) {
        String uniqueId = contentDO.getUniqueId();
        QueryWrapper<DocumentContentPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(DocumentContentPO::getUniqueId, uniqueId);
        DocumentContentPO origin = documentContentMapper.selectOne(queryWrapper);
        if (Objects.isNull(origin)) {
            long id = uidWorker.nextId();
            contentDO.setId(id);
            DocumentContentPO po = new DocumentContentPO(contentDO);
            documentContentMapper.insert(po);
        } else {
            contentDO.setId(origin.getId());
        }
    }

}
